<template>
  <div class="avatar-uploader">
    <el-upload
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      class="avatar-uploader-box"
      accept=".jpg,.jpeg,.png,.gif"
      action="#"
      :http-request="uploadAvatar"
    >
      <div v-if="!imageUrl" class="avatar-uploader-empty">
        <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
      </div>
      <img v-else :src="imageUrl" class="avatar-preview" />
    </el-upload>
    <div class="avatar-text">
      <div class="avatar-title">更换头像</div>
      <div class="avatar-desc">图片格式：jpg, jpeg, png, gif，大小不超过2MB</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { updateUserAvatar } from '@/api/user'

const emit = defineEmits(['success'])

// 图片预览地址
const imageUrl = ref('')

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传的文件只能是图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传的图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const uploadAvatar = async (options) => {
  try {
    const { file } = options
    const formData = new FormData()
    formData.append('avatar', file)
    
    const res = await updateUserAvatar(formData)
    options.onSuccess(res)
  } catch (error) {
    options.onError(error)
  }
}

// 上传成功处理
const handleSuccess = (res) => {
  if (res.data && res.data.url) {
    imageUrl.value = res.data.url
    ElMessage.success('头像上传成功')
    emit('success')
  }
}

// 上传失败处理
const handleError = () => {
  ElMessage.error('头像上传失败')
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
  padding: 20px 0;

  .avatar-uploader-box {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      border-color: #409eff;
    }
  }

  .avatar-uploader-empty {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }

  .avatar-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-text {
    margin-left: 20px;

    .avatar-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .avatar-desc {
      font-size: 12px;
      color: #999;
    }
  }
}
</style> 